package cn.edu.baiyunu.myapplication.ui.screens.transactions.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ShoppingCart
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.data.model.Transaction
import cn.edu.baiyunu.myapplication.ui.screens.transactions.viewmodel.TransactionWithCategory
import cn.edu.baiyunu.myapplication.ui.utils.formatDateTime
import cn.edu.baiyunu.myapplication.ui.utils.formatToDateString
import cn.edu.baiyunu.myapplication.ui.utils.getIconByName
import java.text.NumberFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * 交易组项组件，显示同一天的交易记录
 * 
 * @param dateTimestamp 日期时间戳
 * @param transactions 当天的交易记录列表
 * @param onTransactionClick 交易项点击回调
 * @param modifier 修饰符
 */
@Composable
fun TransactionGroupItem(
    dateTimestamp: Long,
    transactions: List<TransactionWithCategory>,
    onTransactionClick: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxWidth()
    ) {
        // 日期标题
        Text(
            text = formatGroupDate(dateTimestamp),
            color = Color.White.copy(alpha = 0.8f),
            fontSize = 14.sp,
            modifier = Modifier.padding(vertical = 10.dp)
        )
        
        // 交易列表
        transactions.forEach { (transaction, category) ->
            TransactionItem(
                transaction = transaction,
                category = category,
                onClick = { onTransactionClick(transaction.id) }
            )
            
            Spacer(modifier = Modifier.height(10.dp))
        }
    }
}

/**
 * 单个交易项组件
 * 
 * @param transaction 交易记录
 * @param category 交易分类
 * @param onClick 点击回调
 * @param modifier 修饰符
 */
@Composable
fun TransactionItem(
    transaction: Transaction,
    category: Category,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(15.dp))
            .background(Color.White.copy(alpha = 0.1f))
            .clickable(onClick = onClick)
            .padding(15.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 分类图标
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(Color.White.copy(alpha = 0.15f)),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = getIconByName(category.icon),
                contentDescription = category.name,
                tint = Color.White
            )
        }
        
        Spacer(modifier = Modifier.width(15.dp))
        
        // 交易详情
        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = transaction.note.ifEmpty { category.name },
                color = Color.White,
                fontSize = 16.sp,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(5.dp))
            
            Text(
                text = category.name,
                color = Color.White.copy(alpha = 0.7f),
                fontSize = 12.sp
            )
        }
        
        // 交易金额
        Text(
            text = formatAmount(transaction.amount, transaction.type),
            color = if (transaction.type == "expense") Color(0xFFFF5E62) else Color(0xFF26DE81),
            fontWeight = FontWeight.Bold,
            fontSize = 16.sp
        )
    }
}

/**
 * 格式化分组日期显示
 */
@Composable
fun formatGroupDate(timestamp: Long): String {
    val today = Calendar.getInstance().apply {
        set(Calendar.HOUR_OF_DAY, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }
    
    val yesterday = Calendar.getInstance().apply {
        timeInMillis = today.timeInMillis
        add(Calendar.DAY_OF_YEAR, -1)
    }
    
    val date = Calendar.getInstance().apply {
        timeInMillis = timestamp
    }
    
    return when {
        date.timeInMillis == today.timeInMillis -> "今天"
        date.timeInMillis == yesterday.timeInMillis -> "昨天"
        else -> formatToDateString(timestamp)
    }
}

/**
 * 格式化金额显示
 */
fun formatAmount(amount: Double, type: String): String {
    val prefix = if (type == "expense") "-" else "+"
    val formatter = NumberFormat.getCurrencyInstance(Locale.CHINA)
    val formatted = formatter.format(amount).replace("¥", "￥")
    return "$prefix$formatted"
} 